'''
Created on Jun 4, 2009

@author: mkiyer
'''

from veggie.util.eland2bed import convert_elandexport_2_bed, convert_elandresult_2_bed
from veggie.sample.sampledb import get_flowcell_data_path, SampleDB
import os
import sys

def convert_to_tag_format(parser, align_fhd, output_fhd):
    # parse file for reads that map to this chromosome
    for mappings in parser.parse_file(align_fhd):
        for match in mappings:
            if not match.maps_to_genome():
                continue
            if match.chrom == 'chrM':
                continue            
            strand = None            
            if match.strand == 'F' or match.strand == '+':
                strand = '+'
            elif match.strand == 'R' or match.strand == '-':
                strand = '-'
            else:
                # TODO: exception
                print 'strand format error', match.strand
                sys.exit(1)
            # write in "tag" format
            output_fhd.write('%s\t%d\t%s\n' % (match.chrom, match.chrom_start, strand))

def get_exper_name(treatment_name, control_name=None):
    if not control_name:
        return treatment_name + '_vs_None'
    else:
        return treatment_name + '_vs_' + control_name

def _make_filenames(lanes, fileformat):
    for lane in lanes:
        yield 's_' + lane + '_' + fileformat + '.txt'

def _convert_to_bed(bed_fhd, filename, format, do_hpeak=False):
    if format == 'export':    
        convert_elandexport_2_bed(open(filename), bed_fhd, do_hpeak)
    elif format == 'eland_result':
        convert_elandresult_2_bed(open(filename), bed_fhd, do_hpeak)

def convert_sample_to_bed(sample, format, bed_fhd, do_hpeak=False):
    if sample.isPaired:
        s_path = sample.getPath(format, pair=1)
        _convert_to_bed(bed_fhd, s_path, format, do_hpeak)
        s_path = sample.getPath(format, pair=2)
        _convert_to_bed(bed_fhd, s_path, format, do_hpeak)
    else:
        s_path = sample.getPath(format)
        _convert_to_bed(bed_fhd, s_path, format, do_hpeak)

 # TODO: deprecated - remove
def convert_all_to_bed(sample_name, samples, cwd, do_hpeak=False):
    if do_hpeak:
        bed_file = os.path.join(cwd, sample_name + '.hpk')
    else:
        bed_file = os.path.join(cwd, sample_name + '.bed')
    # only create the BED file if it does not already exist
    if (not os.path.isfile(bed_file)):
        bed_fhd = open(bed_file, 'w')
        for sample in samples:
            # unpack sample info
            flowcell, lanes, format = sample[0], sample[1], sample[2]
            # get path to flowcell
            sample_path = get_flowcell_data_path(flowcell)
            if sample_path == None:
                db = SampleDB()
                sample_path = db.get_flowcell_data_path(flowcell)
            # add eland file name to path
            for filename in _make_filenames(lanes, format):
                eland_file = os.path.join(sample_path, filename)
                # convert to BED format
                print >>sys.stderr, 'adding', eland_file, 'to bed file:', bed_file
                # convert export format to BED format
                _convert_to_bed(bed_fhd, eland_file, sample[2], do_hpeak)
        # cleanup
        bed_fhd.close()
    return bed_file